package com.itwizard.mezzofanti;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentProviderOperation;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ResultsActivity1  extends Activity{
	
	String name = "OCRTest";
	String mobNo = "";
	String homeNo = "";
	String workNo = "";
	String email = "";
	
	public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.results1);
        
        EditText editText = (EditText) findViewById(R.id.edittext);
        editText.setText(OCR.m_ssOCRResult);
        Toast.makeText(this, "OCR Confidence Level:"+OCR.m_iMeanConfidence, Toast.LENGTH_LONG).show();
        
        Button contactCard = (Button) findViewById(R.id.btn1);
        Button saveFile = (Button) findViewById(R.id.btn2);
        
        contactCard.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				//OCR Result = OCR.m_ssOCRResult.toString
				Log.i("Result", OCR.m_ssOCRResult.toString());
				String[] strArray = OCR.m_ssOCRResult.toString().split("[\r\n]+");
				Log.i("StrArray Size", strArray.length+"");
				//for(int i=0; i<strArray.length; i++){
					Log.i("StrArray", strArray[0]);
					if(strArray[0].toLowerCase().contains(":")){
						name = strArray[0].split(":")[1];
					}if(strArray[1].toLowerCase().contains(":")){
						mobNo = strArray[1].split(":")[1].replace(".", "");
					}if(strArray[2].toLowerCase().contains(":")){
						homeNo = strArray[2].split(":")[1];
					}
					//if(strArray[i])
				//}
				Log.i("Name", name+",,"+mobNo+",,"+homeNo);
				saveInContacts(name, mobNo, homeNo, workNo, email);
			}
		});
        
        saveFile.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(0);
			}
		});
    }

	

	protected void saveInContacts(String name, String mobno, String homeno, String workno, String email) {
		// TODO Auto-generated method stub
		String DisplayName = name;
        String MobileNumber = mobno;
        String HomeNumber = homeno;
        String WorkNumber = workno;
        String emailID = email;
        String company = "";
        String jobTitle = "";


                           ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
                           ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                                   .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                                   .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                                   .build());

                           //------------------------------------------------------ Names
                           if(DisplayName != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DisplayName).build());
                           }                       
                           //------------------------------------------------------ Mobile Number
                           if(MobileNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                                       .build());
                           }

                           //------------------------------------------------------ Home Numbers
                           if(HomeNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
                                       .build());
                           }

                           //------------------------------------------------------ Work Numbers
                           if(WorkNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
                                       .build());
                           }

                           //------------------------------------------------------ Email
                           if(emailID != null)
                           {
                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                           .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                           .withValue(ContactsContract.Data.MIMETYPE,
                                                   ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                                           .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
                                           .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                                           .build());
                           }

                           //------------------------------------------------------ Organization
                           if(!company.equals("") && !jobTitle.equals(""))
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                                       .build());
                           }

                           // Asking the Contact provider to create a new contact                  
                           try 
                           {
                               getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                               Toast.makeText(ResultsActivity1.this, "Successfully Saved in Contacts", Toast.LENGTH_SHORT).show();
                           } 
                           catch (Exception e) 
                           {               
                               e.printStackTrace();
                               Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                           }


	}
	
	
	 @Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {

	case 0:
        // This example shows how to add a custom layout to an AlertDialog
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
        final EditText edit1 = (EditText) textEntryView.findViewById(R.id.username_edit);
        return new AlertDialog.Builder(ResultsActivity1.this)
            .setIcon(R.drawable.alert_dialog_icon)
            .setTitle("Enter the name of file:")
            .setView(textEntryView)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked OK so do some stuff */
                	if(!edit1.getText().toString().equals("")){
                		saveAsFile(edit1.getText().toString());
                	}else{
                		Toast.makeText(ResultsActivity1.this, "Please enter some name", Toast.LENGTH_SHORT).show();
                	}
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked cancel so do some stuff */
                }
            })
            .create();
    }
    return null;
}

	 protected void saveAsFile(String filename) {
			// TODO Auto-generated method stub
			try{
				  // Create file 
				File f = new File("/sdcard/OCRFiles/");
				if(f.exists())
					;
				else
					f.mkdir();
				  FileWriter fstream = new FileWriter("/sdcard/OCRFiles/"+filename+".txt");
				  BufferedWriter out = new BufferedWriter(fstream);
				  out.write(OCR.m_ssOCRResult.toString());
				  //Close the output stream
				  out.close();
				  Toast.makeText(ResultsActivity1.this, "Successfully Saved under OCRFiles folder in SDCard", Toast.LENGTH_SHORT).show();
				  }catch (Exception e){//Catch exception if any
				  System.err.println("Error: " + e.getMessage());
				  }
		}

}
